﻿using Algorithm.Check;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Algorithm.Check.ExtensionForCRC16;

namespace NewDevice.RS485
{
    /// <summary>
    /// ZH_4424G4不开启主动上传版，单次查询所有通道数据
    /// </summary>
    public class ZH_4424G4_NoAutoUpdate
    {
        private readonly OldSerialBase _serial;
        private readonly int _slaveId;
        private readonly string _deviceName;

        /// <summary>
        /// 量程
        /// </summary>
        public int MeasureRange { get; set; } = 30;

        /// <summary>
        /// 电压量程
        /// </summary>
        public int VolMeasureRange { get; set; } = 30;

        /// <summary>
        /// 电流量程
        /// </summary>
        public int CurMeasureRange { get; set; } = 5;

        public ZH_4424G4_NoAutoUpdate(OldSerialBase bus, int slaveId, string name = "ZH_4424G4采集卡")
        {
            _serial = bus;
            this._slaveId = slaveId;
            this._deviceName = name;
        }

        /// <summary>
        /// 获取所有通道的实际值
        /// </summary>
        public List<double> GetAllChannelReallyValue()
        {
            List<double> values = new List<double>();

            byte[] data = [
                (byte)_slaveId,
                0x03,
                0x00,
                0x00,
                0x00,
                0x18
            ];

            byte[] cmd = data.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
            byte[] registerData = new byte[recv.Length - 5];
            Array.Copy(recv, 3, registerData, 0, registerData.Length);
            for (int i = 0; i < registerData.Length; i += 2)
            {
                if (i + 1 >= registerData.Length) break;

                int registerAddress = i / 2;
                Int16 registerValue = (Int16)((registerData[i] << 8) | registerData[i + 1]);

                values.Add(Math.Round(registerValue * MeasureRange / 10000.0, 4));
            }

            return values;
        }

        /// <summary>
        /// 获取所有通道的原始值
        /// </summary>
        public List<short> GetAllChannelInitValue()
        {
            List<short> values = new List<short>();

            byte[] data = [
                (byte)_slaveId,
                0x03,
                0x00,
                0x00,
                0x00,
                0x18
            ];

            byte[] cmd = data.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
            byte[] registerData = new byte[recv.Length - 5];
            Array.Copy(recv, 3, registerData, 0, registerData.Length);
            for (int i = 0; i < registerData.Length; i += 2)
            {
                if (i + 1 >= registerData.Length) break;

                int registerAddress = i / 2;
                Int16 registerValue = (Int16)((registerData[i] << 8) | registerData[i + 1]);

                values.Add(registerValue);
            }

            return values;
        }

        /// <summary>
        /// 针对12路电压12路电流模块，采集1-12路电压，13-24电流
        /// </summary>
        public Dictionary<string, List<double>> Get12Vol12CurChannelReallyValue()
        {
            List<short> values = new List<short>();
            Dictionary<string, List<double>> pairs = new();
            byte[] data = [
                (byte)_slaveId,
                0x03,
                0x00,
                0x00,
                0x00,
                0x18
            ];

            byte[] cmd = data.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
            byte[] registerData = new byte[recv.Length - 5];
            Array.Copy(recv, 3, registerData, 0, registerData.Length);
            for (int i = 0; i < registerData.Length; i += 2)
            {
                if (i + 1 >= registerData.Length) break;

                int registerAddress = i / 2;
                Int16 registerValue = (Int16)((registerData[i] << 8) | registerData[i + 1]);
                values.Add(registerValue);
                //values.Add(Math.Round(registerValue * MeasureRange / 10000.0, 4));
            }

            if (values.Count==24)
            {
                var result = values.Select((num, index) =>
                index < 12 ? (double)(Math.Round(num* VolMeasureRange / 10000.0, 4))
                : (double)(Math.Round(num* CurMeasureRange / 10000.0, 4))).ToList();
                pairs.Add("电压", result.Take(12).ToList());
                pairs.Add("电流", result.Skip(12).ToList());
            }
            else
            {
                throw new Exception("通道数量错误！");
            }
            return pairs;
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            _serial.Close();
        }
    }
}